package com.algorithm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: sun.hongliang
 * @create: 2019/07/25 11:17
 */
public class ThreeSum {
    public static void main(String[] args) {
    }

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        int length = nums.length;
        for (int i = 0; i < length; i++) {
            int target = nums[i];
            if (target > 0) {
                break;
            }
            int l = i + 1;
            int r = length - 1;
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            while (l < r) {
                if (nums[l] + nums[r] == -target) {
                    result.add(Arrays.asList(nums[l], nums[r], target));
                    while (l < r && nums[l] == nums[l + 1]) {
                        l++;
                    }
                    while (l < r && nums[r] == nums[r - 1]) {
                        r--;
                    }
                    l++;
                    r--;
                } else if (nums[l] + nums[r] > -target) {
                    r--;
                } else {
                    l++;
                }
            }
        }
        return result;
    }
}
